import axios from 'axios'
import router from "@/router";
import {Message} from 'element-ui'

//创建一个axios对象出来
const request = axios.create({
    baseURL: '/api',
    timeout: 10000
})

//request拦截器
//在请求发送前对请求做一些处理
//统一加Token 对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    const user = sessionStorage.getItem("user");
    if (user) {
        config.headers['token'] = JSON.parse(user).token;       //把token加到请求头上
    }

    return config
}, error => {
    return Promise.reject(error)
});

//response 拦截器
//在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        //reponse.data就是后端返回的result
        let res = response.data;
        //兼容服务端返回的字符串数据
        if (typeof res === "string") {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        // console.log(error)
        // console.log(error.response.status)
        // debugger;
        if (error.response.status === 401) {
            // console.log(1)
            Message({
                message:'用户未授权,请登录后再进行操作!',
                type:'error'
            })
            router.push("/loginview");
        }
        return Promise.reject(error);
    }
)

export default request;